/*
* @Author: sc
* @Date:   2018-12-28 18:43:24
* @Last Modified by:   sc
* @Last Modified time: 2019-01-07 23:48:30
*/

'use strict';
require('./index.css');
var _mm 		 = require('util/mm.js');
var templateHtml = require('./index.string');
var page ={
	init : function(){
		//var storage=window.localStorage;
		//storage.clear();
		_mm.initStorage();
		this.bindEvent();
		this.render();
	},
	// 绑定事件
	bindEvent : function(){
		var _this = this;
		// 增加未完成的计划
		$(document).on('click', '.btn-add', function(){
			_this.addThing();
		});
		// 输入框按回车也表示增加
		$('.input-things').keyup(function(e){
			if(e.keyCode === 13){
				_this.addThing();
			}
		})
		// 删除未完成的计划
		$(document).on('click', '.btn-delete', function(){
			var id = $(this).parents('.todo-item').data("todo-id");
			_mm.deleteData('count-new' + id);
			_this.render();
		});
		// 标记未完成的计划为已完成
		$(document).on('click', '.btn-done', function(){
			var id        = $(this).parents('.todo-item').data("todo-id");
			var data 	  = JSON.parse(_mm.getData('count-new' + id)),
				myDate    = new Date(),
				countDone = _mm.getData('count-done');
			data.dtime = myDate.toLocaleString();
			//console.log("done: " + JSON.stringify(data));
			_mm.saveData('count-done' + countDone, JSON.stringify(data));			
			_mm.saveData('count-done', ++countDone);
			_mm.deleteData('count-new' + id);
			_this.render();
		});
		// 清理缓存
		$(document).on('click', '.btn-clear', function(){
			_mm.clearStorage();
			_mm.initStorage();
			_this.render();
		});
	},
	// 增加计划
	addThing : function(){
		var text = $('.input-things').val();
		if(!!text){
			var result = JSON.stringify(_mm.createJson(text)),
				count  = parseInt(_mm.getData('count-new'));
			_mm.saveData('count-new' + count, result);
			_mm.saveData('count-new', ++count);
			this.render()
		}
	},
	// 渲染
	render : function(){
		var data  = {
			'listNew' : [],
			'listDone': []
		};
		var	countNew    = parseInt(_mm.getData('count-new')),
			countDone   = _mm.getData('count-done');
		// 从loackStorage取出未完成的计划
		for(var i = 1; i < countNew; i++){
			var temp = _mm.getData('count-new' + i);//字符串
			if(temp !== 'delete'){
				data.listNew.push(JSON.parse(temp));
			}
		}
		//console.log(data);
		// 从loackStorage取出已完成的计划
		for(var i = 1; i < countDone; i++){
			var temp = _mm.getData('count-done' + i);//字符串
			if(temp !== 'delete'){
				data.listDone.push(JSON.parse(temp));
			}
		}
		// 将渲染好的html放入index.html
		var html = _mm.renderHtml(templateHtml, data);
		$('.info').html(html);
	}
}

page.init();